//
//  NSString+Emoji.m
//  jingduoduo
//
//  Created by diaojz on 16/1/25.
//  Copyright © 2016年 totem. All rights reserved.
//

#import "NSString+Emoji.h"

@implementation NSString (Emoji)

/**
 *  判断是否是中文、ASCIIS可见字符
 */
+ (BOOL)isValidChar:(NSString*)str
{
    __block BOOL returnValue = NO;
    
    [str enumerateSubstringsInRange:NSMakeRange(0, [str length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
       
        const unichar c = [substring characterAtIndex:0];
        
        //英文、数字、中文
        if ((c >= 32 && c <= 126) || (c >= 19968 && c <= 40870)) {
            returnValue = YES;
        } else {
            returnValue = NO;
        }
    }];
    
    return returnValue;
}

/**
 *  遍历字符串，删除所有表情
 */
- (instancetype)removedEmojiString
{
    NSMutableString *__block buffer = [NSMutableString stringWithCapacity:[self length]];
    
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                              [buffer appendString:([substring isEmoji]) ? @"" : substring];
                          }];
    
    return buffer;
}

/**
 *  判断是否是表情
 */
- (BOOL)isEmoji
{
    const unichar high = [self characterAtIndex:0];
    
    // Surrogate pair (U+1D000-1F77F)
    if (0xd800 <= high && high <= 0xdbff) {
        const unichar low = [self characterAtIndex:1];
        const int codepoint = ((high - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000;
        
        return (0x1d000 <= codepoint && codepoint <= 0x1f77f);
        
        // Not surrogate pair (U+2100-27BF)
    } else {
        return (0x2100 <= high && high <= 0x27bf);
    }
}

@end
